// 时间格式化：YYYY-MM-DD HH:MM
export const formatDateTime = (date = new Date()) => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hour = String(date.getHours()).padStart(2, '0');
    const minute = String(date.getMinutes()).padStart(2, '0');
    return `${year}-${month}-${day} ${hour}:${minute}`;
};

// 初始化/获取待审批列表（本地缓存）
export const getPendingList = () => {
    let pending = uni.getStorageSync('teacher_pending');
    if (!pending || pending.length === 0) {
        // 模拟初始数据
        pending = [
            {
                leaveId: 'L001',
                studentName: '张三',
                studentId: '2023001',
                studentClass: '计算机2301班',
                leaveType: '事假',
                startDate: '2024-09-20',
                endDate: '2024-09-21',
                applyTime: formatDateTime(new Date(Date.now() - 3600000)),
                reason: '家中有事，需回家处理'
            },
            {
                leaveId: 'L002',
                studentName: '李四',
                studentId: '2023002',
                studentClass: '数学2302班',
                leaveType: '病假',
                startDate: '2024-09-20',
                endDate: '2024-09-20',
                applyTime: formatDateTime(new Date(Date.now() - 7200000)),
                reason: '感冒发烧，需休息1天'
            }
        ];
        uni.setStorageSync('teacher_pending', pending);
    }
    return pending;
};

// 获取已审批列表（本地缓存）
export const getApprovedList = () => {
    let approved = uni.getStorageSync('teacher_approved');
    return approved ? approved : [];
};

// 审批操作（本地缓存更新）
export const approveLeave = (leaveId, status, remark) => {
    let pending = getPendingList();
    let approved = getApprovedList();
    const leaveIdx = pending.findIndex(item => item.leaveId === leaveId);

    if (leaveIdx === -1) return false;
    // 移到已审批列表并添加审批信息
    const approvedItem = {
        ...pending[leaveIdx],
        approveStatus: status, // 1同意，2拒绝
        approveRemark: remark,
        approveTime: formatDateTime()
    };
    pending.splice(leaveIdx, 1);
    approved.unshift(approvedItem);
    // 更新缓存
    uni.setStorageSync('teacher_pending', pending);
    uni.setStorageSync('teacher_approved', approved);
    return true;
};

// 根据ID获取请假详情
export const getLeaveDetail = (leaveId) => {
    const pending = getPendingList();
    return pending.find(item => item.leaveId === leaveId) || null;
};